import { _decorator, Component, Label, Node, Slider } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GUISlider')
export class GUISlider extends Component {
    @property(Slider)
    slider: Slider | null = null;

    @property(Label)
    label: Label | null = null;

    private _fn: ((progress: number, value: number) => void) | null = null;
    private _min: number = 0;
    private _max: number = 1;

    onLoad() {
        this.slider?.node.on('slide', this._onSlide, this);
    }

    onDestroy() {
        this.slider?.node.off('slide', this._onSlide, this);
    }

    private _onSlide() {
        if (!this.slider) return;
        const progress = this.slider.progress;
        const value = this._min + (this._max - this._min) * progress;
        this._fn?.(progress, value);
    }

    public init(
        name: string,
        option: { defaultValue: number; min: number; max: number },
        fn: (progress: number, value: number) => void,
    ) {
        this._min = option.min;
        this._max = option.max;
        this._fn = fn;
        if (this.slider) {
            const p =
                (option.defaultValue - option.min) /
                (option.max - option.min);
            this.slider.progress = p;
        }
        if (this.label) {
            this.label.string = name;
        }
    }
}
